<?php

namespace App\Handlers\Contact;

use Hanson\Vbot\Contact\Friends;
use Hanson\Vbot\Contact\Groups;
use Hanson\Vbot\Message\Text;
use Illuminate\Support\Collection;
use App\Classes\TaoBao\TaoBaoKe;

class ExperienceGroup
{
    public static function messageHandler(Collection $message, Friends $friends, Groups $groups)
    {
        if ($message['from']['NickName'] === '发发发，财政自由') {
            if ($message['type'] === 'group_change' && $message['action'] === 'ADD') {
                Text::send($message['from']['UserName'], '欢迎新人 ' . $message['invited']);
            }

            if ($message['type'] === 'text') {
                if ($message['sender']['NickName'] === '所有的伟大 源于一个勇敢的开始') {
                    if (str_contains($message['content'], '加人')) {
                        $username = str_replace('加人', '', $message['content']);
                        $friends->add($username, '我是你儿子');
                    }
                }

                if (str_contains($message['content'], '搜人')) {
                    $nickname = str_replace('搜人', '', $message['content']);
                    $members  = $groups->getMembersByNickname($message['from']['UserName'], $nickname, true);
                    $result   = '搜索结果 数量：' . count($members) . "\n";
                    foreach ($members as $member) {
                        $result .= $member['NickName'] . ' ' . $member['UserName'] . "\n";
                    }
                    Text::send($message['from']['UserName'], $result);
                } 

                if ($data = self::getTaoBaoLink($message['content'])) {
                    $content = TaoBaoKe::tbkTpwdCreateRequest($data);
                    Text::send($message['from']['UserName'], $content['data']['model']);
                } else {
                    $content = str_replace(' ', '', $message['content']);
                    //发送到图灵机器人接口
                    $url = "http://www.tuling123.com/openapi/api?key=c407416112434017a7e3431bdcf7b417&info=" . $content;
                    // 获取图灵机器人返回的内容
                    $content = file_get_contents($url);
                    // 对内容json解码
                    $content = json_decode($content);
                    Text::send($message['from']['UserName'], $content->text);
                }
            }
        }
    }

    public static function getTaoBaoLink($content)
    {
        $responseData = [];
        $url          = '';
        # 20170909新版淘宝分享中没有链接， 感谢网友jindx0713（https://github.com/jindx0713）提供代码和思路，现在使用第三方网站 http://www.taokouling.com 根据淘口令获取url
        $taokoulingurl = 'http://www.taokouling.com/index.php?m=api&a=taokoulingjm';
        $username      = 'tianmac';
        $password      = 'tkltianmac';
        if (preg_match("/【.*】/", $content, $matches) && (strpos($content, '打开👉手机淘宝👈') !== false || strpos($content, '打开👉天猫APP👈') !== false || strpos($content, '打开👉手淘👈') !== false || strpos($content, '👉淘♂寳♀👈') !== false)) {
            $title = '';
            if (isset($matches[0])) {
                $title = $matches[0];
                $title = str_replace('【', '', $title);
                $title = str_replace('】', '', $title);
            }
            try {
                if (preg_match('/€.*?€/', $content, $matches) && isset($matches[0])) {
                    $taokouling = $matches[0];
                    //初始化
                    $curl = curl_init();
                    //设置抓取的url
                    curl_setopt($curl, CURLOPT_URL, $taokoulingurl);
                    //设置头文件的信息作为数据流输出
                    curl_setopt($curl, CURLOPT_HEADER, 0);
                    //设置获取的信息以文件流的形式返回，而不是直接输出。
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                    //设置post方式提交
                    curl_setopt($curl, CURLOPT_POST, 1);
                    //设置post数据
                    $post_data = [
                        "username" => $username,
                        "password" => $password,
                        "text"     => $taokouling,
                    ];
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
                    //执行命令
                    $responseData = curl_exec($curl);
                    //关闭URL请求
                    curl_close($curl);
                    $responseData = json_decode($responseData, true);
                    $url          = str_replace('https://', 'http://', $responseData['url']);
                }

                // $pattern = '/http:\/\/.* /';
                // preg_match($pattern, $content, $matches);
                // echo '<pre>';
                // echo '正则匹配url:';
                // print_r($matches);
                // if (isset($matches[0])) {
                //     $url = $matches[0];
                // }

            } catch (Exception $e) {
                $url = '';
            }
        }

        if (empty($url)) {
            if (preg_match('/￥.*?￥/', $content, $matches) && isset($matches[0])) {
                $taokouling = $matches[0];

                //初始化
                $curl = curl_init();
                //设置抓取的url
                curl_setopt($curl, CURLOPT_URL, $taokoulingurl);
                //设置头文件的信息作为数据流输出
                curl_setopt($curl, CURLOPT_HEADER, 0);
                //设置获取的信息以文件流的形式返回，而不是直接输出。
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                //设置post方式提交
                curl_setopt($curl, CURLOPT_POST, 1);
                //设置post数据
                $post_data = [
                    "username" => "tianmac",
                    "password" => "tkltianmac",
                    "text"     => $taokouling,
                ];
                curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
                //执行命令
                $responseData = curl_exec($curl);
                //关闭URL请求
                curl_close($curl);
                //显示获得的数据
                $responseData = json_decode($responseData, true);
                $url          = str_replace('https://', 'http://', $responseData['url']);
            }
        }

        if (!empty($url)) {
            $arr = parse_url($url);
            // 指定第二个参数
            parse_str($arr['query'], $arr1);
            // 商品id
            $itemId = $arr1['id'];
            $responseData['detail_url'] = 'https://uland.taobao.com/coupon/edetail?itemId=' . $itemId . '&activityId=';
        }
        return $responseData;
    }
}
